﻿using System;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Serialization;
using SpCop.Model;

namespace SpCop
{
    internal class RulesReader
    {
        private static readonly Type RuleSetType = typeof (RuleSet);
        private static readonly XmlSerializer Serializer = new XmlSerializer(RuleSetType);

        internal static RuleSet ReadRulesFromAssembly(Assembly assembly, string resource)
        {
            using (Stream stream = assembly.GetManifestResourceStream(resource))
            {
                if (stream == null)
                    throw new InvalidOperationException("Failed to read stream from assembly.");
                else
                    using (XmlReader reader = XmlReader.Create(stream))
                    {
                        RuleSet set = ReadRulesFromXmlReader(reader);
                        set.Assembly = assembly;
                        return set;
                    }
            }
        }

        internal static RuleSet ReadRulesFromXmlReader(XmlReader reader)
        {
            object deserializedRules = Serializer.Deserialize(reader);
            return (RuleSet) deserializedRules;
        }
    }
}